package com.uchengwang.ui.cm_ui.rychat.manager;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.RyConfig;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.cm_ui.rychat.msgtype.UcTypeMessage;
import com.uchengwang.ui.cm_ui.ucity.cityBean.UcityInfoBean;
import com.uchengwang.ui.cm_ui.umsg.bean.ClubAccessBean;
import com.uchengwang.ui.cm_ui.uu.bean.SpeekBean;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;

/**
 * Created by U城网 on 2017/6/26.
 * 融云操作
 */

public class RongChatManager {
    private static RongChatManager utils;
    // 记录是否已经初始化
    private boolean isInit = false;
    private RongChatManager(){}

    public static RongChatManager getUtils() {
        if (utils == null){
            utils = new RongChatManager();
        }
        return utils;
    }

    /**
     * 判断有没有存储融云token 没有请求网络并存储 连接到融云  有 则直接连接融云
     * @param listener 连接融云服务器给回调 可以传null
     * */
    public void getTokenAdnLink(final Context context, final OnResultListener listener){
        Log.d("ryjjf", "去连接融云");
        String token = SPUtils.getPreferences(context).getRyToken();
        if (!TextUtils.isEmpty(token)){
            //直接连接到融云
            linkToRy(context, token, listener);
        }else {
            getToken((Activity) context, new OnResultListener() {
                @Override
                public void onResult(int stutas, String msg, int total, String data) {
                    Log.d("ryjjf", "获取融云token=stutas="+stutas+"=msg="+msg);
                    if (stutas ==0 && !TextUtils.isEmpty(data)){
                        //请求成功 获取token 并将token储存起来
                        SPUtils.getPreferences(context).setRyToken(data);
                        linkToRy(context, data, listener);
                    }
                }
            });
        }
    }

    /**
     * 连接到融云
     * */
    private void linkToRy(final Context context, String token, final OnResultListener listener){
        if (context.getApplicationInfo().packageName.equals(UCommonUtil.getUtil().getCurProcessName(context.getApplicationContext()))){
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    //Connect Token 失效的状态处理，需要重新获取 Token 我们设置的永久有效
                    getToken((Activity) context, new OnResultListener() {
                        @Override
                        public void onResult(int stutas, String msg, int total, String data) {
                            if (stutas ==0 && !TextUtils.isEmpty(data)){
                                //请求成功 获取token 并将token储存起来
                                SPUtils.getPreferences(context).setRyToken(data);
                                linkToRy(context, data, listener);
                            }
                        }
                    });
                }

                @Override
                public void onSuccess(String s) {
                    Log.d("ryjjf", "连接融云成功");
                    EventBus.getDefault().post(true);
                    String headUrl = "";
                    if (TextUtils.isEmpty(UChengApplication.userAvatar)){
                        headUrl = "http://ucw-user.oss-cn-shanghai.aliyuncs.com/default_image.jpg";
                    }else {
                        headUrl = UChengApplication.userAvatar;
                    }
                    UserInfo info = new UserInfo(String.valueOf(UCommonUtil.getUtil().getId()), UChengApplication.nickName, Uri.parse(headUrl));
                    RongIM.getInstance().setCurrentUserInfo(info);
                    RongIM.getInstance().refreshUserInfoCache(info);
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
                    if (listener != null){
                        //连接融云成功
                        listener.onResult(0, "连接融云成功", 0, s);
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    String msg = errorCode.getMessage();
                    int code = errorCode.getValue();
                    Log.d("ryjjf", "code="+code+"=msg="+msg);
                    if (listener != null){
                        //连接融云成功
                        listener.onResult(code, "msg", 0, null);
                    }
                }
            });
        }
    }

    /**
     * 从服务器获取融云token
     * */
    private void getToken(Activity activity, final OnResultListener listener){
        HttpManager.newInstance(activity).query(RyConfig.Token.method, RyConfig.Token.URL, null, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("ryjjf", "stutas="+status+"=msg="+msg);
                if (listener !=null){
                    listener.onResult(status, msg, 0, null);
                }
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("ryjjf", "stutas="+status+"=data="+data);
                if (status ==0 && !TextUtils.isEmpty(data)){
                    JSONObject object = JsonUtils.getManager().getJSONObject(data);
                    String token = object.getString("token");
                    if (listener != null){
                        listener.onResult(status, msg, 0, token);
                    }
                }else {
                    listener.onResult(status, msg, 0, null);
                }

            }
        });
    }

    /**
     * 切换融云账号
     * 1,跳到MainActivity[社团切换到个人]  2，跳到ClubMainActivity【个人切换到社团】
     * */
    public void changeRy(Context context){
        Log.d("ryjjf", "退出融云");
        RongIM.getInstance().logout();//退出
        UChengApplication.isAccountChange = true;
//        getTokenAdnLink(context, null);
    }

    /**
     * 加入黑名单
     * @param isAddToBlack true 加入黑名单
     * */
    public void addOrRemoveBlacklist(boolean isAddToBlack, final long userId, final OnResultListener listener){
        if (isAddToBlack){
            RongIM.getInstance().addToBlacklist(String.valueOf(userId), new RongIMClient.OperationCallback() {
                @Override
                public void onSuccess() {
                    listener.onResult(0, "", 0, "");
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.d("ryjjf", "加入黑名单code="+errorCode.getValue()+"=msg="+errorCode.getMessage());
                    listener.onResult(-1, "", 0, "");
                }
            });
        }else {
            RongIM.getInstance().removeFromBlacklist(String.valueOf(userId), new RongIMClient.OperationCallback() {
                @Override
                public void onSuccess() {
                    listener.onResult(0, "", 0, "");
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.d("ryjjf", "移除黑名单code="+errorCode.getValue()+"=msg="+errorCode.getMessage());
                    listener.onResult(-1, "", 0, "");
                }
            });
        }
    }

    /**
     * 查询某个用户是否在黑名单中
     * */
    public void getBlackById(long userId, final OnResultListener listener){
        RongIM.getInstance().getBlacklistStatus(String.valueOf(userId), new RongIMClient.ResultCallback<RongIMClient.BlacklistStatus>() {
            @Override
            public void onSuccess(RongIMClient.BlacklistStatus blacklistStatus) {
                if (blacklistStatus == RongIMClient.BlacklistStatus.IN_BLACK_LIST){
                    //在黑名单里
                    listener.onResult(0, "", 0, "");//0在黑名单  -1不在
                }else {
                    listener.onResult(-1, "", 0, "");
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.d("ryjjf", "检查是否在黑名单code="+errorCode.getValue()+"=msg="+errorCode.getMessage());
                listener.onResult(-1, "", 0, "");
            }
        });
    }

    /**
     * 融云发送一个文本消息
     * */
    public void sendTextMsg(String con, long uid, Conversation.ConversationType type){
        TextMessage myTextMessage = TextMessage.obtain(con);
        senMsg(myTextMessage, String.valueOf(uid), type);
    }


    /**
     * 发送自定义消息
     * 每条消息统一带入参数 :个人头像 "userAvatar" :"自己的头像地址"	个人昵称 "nickName":"自己的昵称"
     转发U城消息 带入扩展字段 "isUcw":"true" //是不是U城网转发消息 true是
     "content":"{"title":"标题","content":"内容描述", "cover":"背景图", "id":"信息ID", "type":"信息类型"}"
     @param content 发送内容
     @param uid 被发送人/群 ID
     * */
    public void senMsg(MessageContent content, String uid, Conversation.ConversationType type){
        Message msg = Message.obtain(uid, type, content);
        //send message
        RongIM.getInstance().sendMessage(msg, null, null, new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(Message message) {

            }

            @Override
            public void onSuccess(Message message) {

            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {

            }
        });

        Toast.makeText(UChengApplication.getContext(), "发送成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 封装要发送的U城消息 跳转到选择好友界面
     * type //1-U学，2-U赛，3-U行，4-U用，5-U公益活动倡议，6-U公益失物招领,7-社团活动, 8-社团分享)  9校吧帖子
     * 10社团纳新[当为社团纳新时, ID为社团账号]  11 享说动态 12推荐群
     * */
    public void createMsg(UcTypeMessage message, Context context){
//        Intent in = new Intent(context, FansActivity.class);
//        in.putExtra(BaseConfig.UID, UCommonUtil.getUtil().getId());
//        in.putExtra(BaseConfig.TYPE, 3);
//        in.putExtra(BaseConfig.IS_SEND, true);
//        in.putExtra(BaseConfig.BEAN, message);
//        in.putExtra(BaseConfig.IS_TO_GROUP, true);
//        context.startActivity(in);
    }

    /**
     * 封装要发送的U城消息 跳转到选择好友界面
     * type //1-U学，2-U赛，3-U行，4-U用，5-U公益活动倡议，6-U公益失物招领,7-社团活动, 8-社团分享)  9校吧帖子
     * 10社团纳新[当为社团纳新时, ID为社团账号]  11 享说动态  12推荐群[当为推荐群时 id为群ID title:群名称 content:群描述 cover:群logo ]
     * */
    public void createMsg(UcityInfoBean bean, Context context){
        UcTypeMessage message = new UcTypeMessage();
        message.setUcTitle(bean.getPubTitle());
        message.setUcContent(bean.getPubShortDesc());
        message.setUcCover(bean.getPubShortCover());
        message.setUcType(bean.getPubType());
        message.setUcId(bean.getId());

//        Intent in = new Intent(context, FansActivity.class);
//        in.putExtra(BaseConfig.UID, UCommonUtil.getUtil().getId());
//        in.putExtra(BaseConfig.TYPE, 3);
//        in.putExtra(BaseConfig.IS_SEND, true);
//        in.putExtra(BaseConfig.BEAN, message);
//        in.putExtra(BaseConfig.IS_TO_GROUP, true);
//        context.startActivity(in);
    }
    /**
     * 封装要发送的享说 跳转到选择好友界面
     * */
    public void createMsg(SpeekBean bean, Context context){
        UcTypeMessage message = (UcTypeMessage) createMsg(bean.getId(), bean.getContent(), bean.getContent(), (bean.getPhotos() != null && bean.getPhotos().size() >0) ? bean.getPhotos().get(0) : "",
                BaseConfig.SPEEK_TYPE);

//        Intent in = new Intent(context, FansActivity.class);
//        in.putExtra(BaseConfig.UID, UCommonUtil.getUtil().getId());
//        in.putExtra(BaseConfig.TYPE, 3);
//        in.putExtra(BaseConfig.IS_SEND, true);
//        in.putExtra(BaseConfig.BEAN, message);
//        in.putExtra(BaseConfig.IS_TO_GROUP, true);
//        context.startActivity(in);
   }
    /**
     * 封装要发送的社团纳新 跳转到选择好友界面
     * */
    public void createMsg(ClubAccessBean bean, Context context){
        UcTypeMessage message = (UcTypeMessage) createMsg(bean.getOrgId(), bean.getRecruitTitle(), bean.getRecruitTitle(), bean.getCover(), BaseConfig.CLUB_NEW_MEMBER);

//        Intent in = new Intent(context, FansActivity.class);
//        in.putExtra(BaseConfig.UID, UCommonUtil.getUtil().getId());
//        in.putExtra(BaseConfig.TYPE, 3);
//        in.putExtra(BaseConfig.IS_SEND, true);
//        in.putExtra(BaseConfig.BEAN, message);
//        in.putExtra(BaseConfig.IS_TO_GROUP, true);
//        context.startActivity(in);
    }

    /**
     * 创建发送消息体
     * */
    public MessageContent createMsg(long id, String title, String descr, String cover, int type){
        UcTypeMessage message = new UcTypeMessage();
        message.setUcTitle(title);
        message.setUcCover(cover);
        message.setUcId(id);
        message.setUcType(type);

        String desc = descr;
        if (!TextUtils.isEmpty(desc)){
            if (desc.length() >30){
                desc = desc.substring(0, 30);
            }
            message.setUcContent(descr);
        }else {
            message.setUcContent(descr);
        }

        return message;
    }

}
